package com.kede.api.order.service.impl;

import com.kede.api.ienum.UserMoneyType;
import com.kede.api.order.service.IUserService;
import com.kede.domain.UserMoneyLogDomain;
import com.kede.domain.UsersDomain;
import com.kede.exception.BadRequestException;
import com.kede.service.UserMoneyLogService;
import com.kede.service.UsersService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @Author:Pr.li
 * @Date: create in 2023/7/14 0:15
 */
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UsersService usersService;

    @Resource
    private UserMoneyLogService userMoneyLogService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void actionMoney(Integer userId, BigDecimal money,String ordersn,UserMoneyType userMoneyType) {
        UsersDomain user = usersService.getById(userId);
        String message = "";
        switch (userMoneyType){
            case ZHI:
                message = "置换确认增加余额";
                break;
            case VAILD:
                message = "验收款到账";
                break;
            case SHOPPING:
                message = "商品购物";
        }
        if (message.isEmpty()){
            throw new BadRequestException("userMoneyType无效");
        }
        UserMoneyLogDomain userMoneyLogDomain = new UserMoneyLogDomain();
        userMoneyLogDomain.setBefore(user.getUserMoney());
        userMoneyLogDomain.setMoney(money);
        BigDecimal after = user.getUserMoney().add(money);
        userMoneyLogDomain.setAfter(after);
        userMoneyLogDomain.setMemo(message);
        userMoneyLogDomain.setUserId(userId);
        userMoneyLogDomain.setChangeType(userMoneyType.getCode());
        userMoneyLogDomain.setOrderSn(ordersn);
        Long l = LocalDateTime.now().toEpochSecond(ZoneOffset.ofHours(8));
        userMoneyLogDomain.setCreatetime(l.intValue());
        userMoneyLogService.save(userMoneyLogDomain);
        user.setUserMoney(after);
        usersService.updateById(user);
        return;
    }

}
